import Vue from 'vue'
import Vuex from 'vuex'
import {apiGetMessageList, login, apiGetMessageInfo} from '../api/topics'
import { Message } from 'element-ui'
import { productList, abstractProductList, } from '../pages/main/Products/productList.js'
Vue.use(Vuex)
import axios from 'axios'
export const createStore = () => {
    return new Vuex.Store({
        state: () => ({
            newsList: [],
            newsInfo:{},
            stockInfo:{},
            productTemplate:'',
            productLocation:'',
            cityList:[],
        }),
        mutations: {
            setNewsList(state, data) {
                state.newsList = data
            },
            setNewsInfo(state, data) {
                state.newsInfo = data
            },
            setStockInfo(state, data) {
                state.stockInfo = data
            },
            setProductInfo(state, data){
                state.productTemplate = data.template;
                state.productLocation = data.name;
            },
            setCityList(state, cityList){
                state.cityList = cityList;
            }
        },
        actions: {
            //需要通过服务器渲染的接口数据必须通过vuex
            // action必须返回一个Promise
            GET_NEWS_LIST({ commit },{language}) {
                return apiGetMessageList({businessType:1,language}).then(res=>{  
                    commit('setNewsList', res.data.data.records||[]);
                })
            },
            GET_NEWS_INFO({commit}, {messageId}){
                return apiGetMessageInfo({messageId}).then(res=>{
                    console.log(res.data.data)
                    commit('setNewsInfo', res.data.data||{});
                })
            },
            testLogin() {
                Message.success("hello");
                let form = new FormData();
                form.append("username", "admin");
                form.append("password", "admin");
                return login(form).then(()=>{
                    return 'login'
                });

                
            },
            GET_STOCK_DATA({commit}){
                return axios.get('http://qt.gtimg.cn/q=sh000001',{responseType:'text'})
                    .then(res=>{
                        const _stockData = res.data;
                        let stockData = []
                        if(_stockData){
                            if(_stockData.split('\"').length===3){
                                stockData = _stockData.split('\"')[1].split('~')
                            }
                        }
                        // console.log(stockData,'stock') //[股票名字, 今日开盘价, 昨日收盘价, 当前价格, 今日最高价, 今日最低价, 竞买价, 竞卖价, 成交股票数, 成交金额......]
                        const stockName = stockData[1]
                        const openingPrice = stockData[5];// 开盘价
                        const closingPrice = stockData[4];// 昨日收盘价
                        const currentPrice = stockData[3];// 当前价格
                        const highestPrice = stockData[33];// 今日最高价
                        const lowestPrice = stockData[34];// 今日最低价
                        const increase = (currentPrice -  closingPrice).toFixed(2); // 涨幅
                        const increaseRatio = ((currentPrice -  closingPrice) / closingPrice * 100).toFixed(2) + '%'; // 涨率
                        const volume = (stockData[36]/100).toFixed(2);// 成交量
                        const turnover = (stockData[9]/10).toFixed(2);// 成交额
                        const timeStr = stockData[30]
                        const yymmdd = timeStr.slice(0,4)+'/'+timeStr.slice(4,6)+'/'+timeStr.slice(6,8);
                        const hhmmss = timeStr.slice(8,10)+':'+timeStr.slice(10,12)+':'+timeStr.slice(12,14);
                        const stockInfo = {
                            stockName, openingPrice, closingPrice, highestPrice, lowestPrice, currentPrice,
                            increase, increaseRatio, volume, turnover, yymmdd, hhmmss
                        }
                        commit('setStockInfo', stockInfo)
                    })
            },
            SET_PRODUCT_INFO({commit},pathMatch){
                return new Promise((resolve, _)=>{
                    // 根据match查询location和template TODO: 404处理
                    let location = ''
                    const pathArr = pathMatch.split('/')
                    let len = pathArr.length, i=0;
                    let currentTemplate = '';
                    let currentProductList = abstractProductList
                    while(i<len&&currentProductList){
                        let idx = currentProductList.findIndex(product=>product.link===pathArr[i])
                        if(idx>=0){
                            location = location + ' / ' + currentProductList[idx].name;
                            currentTemplate = currentProductList[idx].template;
                            currentProductList = currentProductList[idx].children;
                            
                        }else{
                            currentProductList = undefined
                        }
                        i++;
                    }
                    


                    const product = productList[4]
                    commit('setProductInfo', {template:currentTemplate,name:location});
                    resolve(product)
                })
            },
            GET_CITY_LIST({commit},language){
                return new Promise((resolve)=>{
                   const cityList = require('./ChinaCityList.json').map(item=>{
                        return {
                            name:language==='en'?item.name_en.replace(item.name_en[0], item.name_en[0].toUpperCase()):item.name
                        }
                    })
                    commit('setCityList', cityList);
                    resolve(cityList)
                })
            }
        }
    })
}